<template>
  <el-card class="custom-card">
    <!-- 卡片顶部区域 -->
    <div class="flex flex-col">

      <!-- 大标题 -->
      <h1 class="contact-title">
        材料基因型文件上传
      </h1>

      <div class="custom-double-divider">
        <el-divider class="title-divider" />
      </div>

      <!-- 支持的数据类型描述 -->
      <div class="service-section">
        <h2 class="section-title">支持的数据类型</h2>
        <div class="case-content">
          <p class="case-text">
            本平台支持多种基因型数据的文件上传，包括但不限于SNP标记数据、基因分型数据、分子标记数据等。上传的数据将用于后续的基因型分析、群体遗传结构研究、关联分析等生物信息学分析。
          </p>
          <p class="case-text">
            文件格式要求：TXT文本格式，文件编码建议使用UTF-8，数据内容应包含样本ID、标记位点信息等基本字段，支持表格形式或特定分隔符格式的数据文件。
          </p>
          <p class="case-text">
            注意事项：请确保上传文件的完整性和准确性，文件大小不超过50MB，单个文件最多支持10,000个样本和100,000个标记位点的数据。
          </p>
        </div>
      </div>

      <!-- 文件上传区域 -->
      <div class="service-section">
        <h2 class="section-title">文件上传</h2>
        <div class="upload-content">
          <el-form :model="form" class="upload-form" ref="uploadFormRef">
            <el-form-item class="form-item-spacing">
              <el-upload
                  class="upload-dragger centered-upload"
                  drag
                  action="/api/upload"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-change="handleFileChange"
                  :before-remove="beforeRemove"
                  :auto-upload="false"
                  :file-list="fileList"
                  accept=".txt"
              >
                <el-icon class="el-icon--upload">
                  <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                  将TXT文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传TXT格式文件（每次只能上传一个文件，文件大小不超过50MB）
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item class="form-item-spacing button-group">
              <div class="buttons-container">
                <el-button
                    class="reset-btn"
                    @click="handleReset"
                >
                  重置
                </el-button>
                <el-button
                    type="danger"
                    class="submit-btn"
                    @click="handleSubmit"
                    :loading="isSubmitting"
                >
                  提交
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </div>

    <!-- 结果对话框 -->
    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
    >
      <span>{{ resultDialogMessage }}</span>
      <template #footer>
        <div style="text-align: center">
          <el-button @click="resultDialogVisible = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus'
// 根据实际API路径引入
// import { genotypeUploadTask } from '~/api/genotypeApi'

const form = reactive({
  // 可以添加其他表单字段
})

const fileList = ref<UploadUserFile[]>([])
const isSubmitting = ref(false)
const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')
const uploadFormRef = ref()

const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件，请先移除已选择的文件')
}

const beforeRemove = () => {
  return ElMessageBox.confirm('确定移除该文件吗？')
}

const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  // 确保只保留一个文件
  if (files.length > 1) {
    fileList.value = [files[files.length - 1]] // 只保留最新上传的文件
  } else {
    fileList.value = files as UploadUserFile[]
  }

  // 检查文件类型
  const isTxt = file.raw?.type === 'text/plain' || file.name?.toLowerCase().endsWith('.txt')
  if (!isTxt) {
    ElMessage.warning('请上传TXT格式的文件')
    fileList.value = []
    return false
  }

  // 检查文件大小（50MB限制）
  const maxSize = 50 * 1024 * 1024 // 50MB
  if (file.raw && file.raw.size > maxSize) {
    ElMessage.warning('文件大小不能超过50MB')
    fileList.value = []
    return false
  }
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    if (fileList.value.length === 0) {
      showResultDialog('错误', '请先选择要上传的文件')
      return
    }

    const file = fileList.value[0].raw
    if (!file) {
      showResultDialog('错误', '文件无效')
      return
    }

    const formData = new FormData()
    formData.append('file', file)
    formData.append('fileType', 'genotype')

    // 调用上传API
    // const response = await genotypeUploadTask(formData)

    // 模拟API调用
    const response = await simulateUpload(formData)

    if (response?.success) {
      showResultDialog('成功', '基因型文件上传成功！文件已进入处理队列，请等待分析结果。')
      fileList.value = [] // 清空文件列表
    } else {
      showResultDialog('错误', response.msg || '文件上传失败，请重试')
    }

  } catch (error) {
    console.error('上传出错:', error)
    showResultDialog('错误', '文件上传失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 模拟上传函数（实际使用时替换为真实API调用）
const simulateUpload = (formData: FormData): Promise<any> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        msg: '上传成功',
        data: {
          fileId: 'genotype_' + Date.now(),
          fileName: formData.get('file')?.name || 'unknown',
          uploadTime: new Date().toISOString()
        }
      })
    }, 2000)
  })
}

const handleReset = () => {
  fileList.value = []
  uploadFormRef.value?.resetFields()
  ElMessage.success('已重置表单')
}

const showResultDialog = (title: string, message: string) => {
  resultDialogTitle.value = title
  resultDialogMessage.value = message
  resultDialogVisible.value = true
}
</script>

<style scoped>
/* 自定义卡片样式 */
.custom-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  transition: all 0.3s ease;
  max-width: 900px;
  margin: 0 auto;
}

.custom-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

/* 标题样式 */
.contact-title {
  font-size: 35px;
  font-weight: bold;
  color: #333;
  text-align: start;
  margin-bottom: 2rem;
}

/* 内容区域样式 */
.platform-content {
  line-height: 1.8;
  color: #555;
  margin-bottom: 2rem;
}

.content-paragraph {
  margin-bottom: 1.5rem;
  text-align: left;
  text-indent: 2em;
}

/* 筛选案例样式 */
.case-content {
  background-color: #f0f9ff;
  padding: 1.5rem;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
  margin-bottom: 2rem;
}

.case-text {
  line-height: 1.6;
  color: #555;
  margin-bottom: 0.8rem;
  text-align: left;
  font-size: 1.05rem;
}

.case-text:last-child {
  margin-bottom: 0;
}

.case-link {
  color: #1890ff;
  text-decoration: none;
  transition: color 0.3s;
}

.case-link:hover {
  color: #096dd9;
  text-decoration: underline;
}

/* 服务部分样式 */
.service-section {
  margin-bottom: 0.5rem;
}

.section-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #13675b;
  margin-bottom: 1rem;
  text-align: start;
}

/* 上传内容样式 */
.upload-content {
  padding: 0 1rem;
}

.upload-form {
  margin-top: 10px;
  max-width: 100%;
}

.form-item-spacing {
  margin-bottom: 22px;
}

.button-group {
  margin-top: 30px;
}

.buttons-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  width: 100%;
}

.submit-btn {
  width: 150px;
  background-color: #1b9382;
  border: none;
  color: white;
}

.reset-btn {
  width: 150px;
  border: 1px solid #1b9382;
  color: #1b9382;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 20px;
}

.centered-upload {
  width: 100%;
}

:deep(.el-upload-dragger:hover),
:deep(.el-upload:focus .el-upload-dragger) {
  border-color: #1b9382;
  color: #1b9382;
}

:deep(.el-upload-dragger .el-icon--upload) {
  color: #1b9382;
  font-size: 48px;
  margin-bottom: 16px;
}

:deep(.el-upload-dragger:hover .el-icon--upload),
:deep(.el-upload:focus .el-upload-dragger .el-icon--upload) {
  color: #1b9382;
}

:deep(.el-form-item) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  justify-content: center;
  margin-left: 0 !important;
}

:deep(.el-upload-dragger) {
  background-color: #fafafa;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #1b9382;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 16px;
  margin-bottom: 10px;
}

:deep(.el-upload__text em) {
  color: #1b9382;
  font-style: normal;
}

/* 分隔线样式 */
.custom-double-divider {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
}

.title-divider {
  position: relative;
  border: none;
  margin: 0;
  height: 1px;
}

/* 左侧 20% 的分隔线（绿色） */
.title-divider::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 20%;
  height: 4px;
  background: #13675b;
}

/* 右侧 80% 的分隔线（灰色） */
.title-divider::after {
  content: "";
  position: absolute;
  right: 0;
  top: 0;
  width: 80%;
  height: 1px;
  background: #e5e7eb;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .custom-card {
    padding: 1.5rem;
  }

  .contact-title {
    font-size: 1.8rem;
  }

  .section-title {
    font-size: 1.3rem;
  }

  .content-paragraph,
  .case-text,
  .process-text,
  .type-text,
  .contact-text,
  .address-text,
  .payment-text {
    font-size: 1rem;
    text-indent: 1.5em;
  }

  .case-content {
    padding: 1rem;
  }

  .upload-content {
    padding: 0;
  }

  .buttons-container {
    flex-direction: column;
    gap: 10px;
  }

  .submit-btn,
  .reset-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .contact-title {
    font-size: 1.5rem;
  }

  .section-title {
    font-size: 1.2rem;
  }

  .content-paragraph,
  .case-text,
  .process-text,
  .type-text,
  .contact-text,
  .address-text,
  .payment-text {
    font-size: 0.9rem;
    text-indent: 1em;
  }

  :deep(.el-upload-dragger) {
    padding: 15px;
  }

  :deep(.el-upload__text) {
    font-size: 14px;
  }
}
</style>